﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PhysicsControlModule.Models;

namespace PhysicsControlModule.Daos
{
    public class CtrlQuestionDao
    {
        public static int GetCount(int labworkId)
        {
            using (CmDbEntities db = new CmDbEntities())
                return (
                        from cq in db.CtrlQuestion
                        from rlcq in db.RelLabworkCtrlQuestion
                        where rlcq.LabworkId == labworkId
                        where rlcq.ControlQuestionId == cq.Id
                        select cq).Count();
        }

        public static int GetAnsweredCount(int labworkId, int userId)
        {
            using (CmDbEntities db = new CmDbEntities())
                return (
                        from cq in db.CtrlQuestion 
                        from rlcqu in db.RelLabworkCtrlQuestionUser 
                        where rlcqu.LabworkId == labworkId
                        where rlcqu.UserId == userId
                        where rlcqu.ControlQuestionId == cq.Id 
                        select cq).Count();
        }

        public static CtrlQuestion GetUnanswered(int labworkId, int userId)
        {
            using (CmDbEntities db = new CmDbEntities())
                return (
                        from cq in db.CtrlQuestion

                        from rlcq in db.RelLabworkCtrlQuestion
                        where rlcq.ControlQuestionId == cq.Id
                        where rlcq.LabworkId == labworkId

                        where !db.RelLabworkCtrlQuestionUser.Any(
                                rlcqu => rlcqu.ControlQuestionId == cq.Id && 
                                rlcqu.UserId == userId && 
                                rlcqu.LabworkId == labworkId)

                        select cq).FirstOrDefault();
        }
    }
}